package cn.codewen.shop.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JDBCUtils {
    private static Connection conn;
    private static String driver;
    private static String url;
    private static String user;
    private static String password;

    static {

        //1. 创建properties对象
        Properties pro = new Properties();
        //2. 通过类加载器加载jdbc.properties文件
        InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
        //3. 把jdbc.properties文件内容映射到pro对象中
        try {
            pro.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //4. 把对应的属性分别赋值
        driver = pro.getProperty("driver");
        url = pro.getProperty("url");
        user = pro.getProperty("user");
        password = pro.getProperty("password");
    }

    /**
     * 连接数据库
     * @return 连接
     */
    public static Connection getConnection(){

        //1.注册驱动
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        //2.建立连接
        try {
            conn = DriverManager.getConnection(url, user, password);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return conn;
    }

    /**
     * 关闭对象
     * @param rs 结果集
     * @param stm stm对象
     * @param conn 连接对象
     * @throws SQLException
     */
    public static void close(ResultSet rs, Statement stm, Connection conn) throws SQLException {

        if (rs != null) {
            rs.close();
        }
        if (stm != null) {
            stm.close();
        }
        if (conn != null) {
            conn.close();
        }

    }
}
